package com.gainloop.Api;

import java.util.ArrayList;

import org.alexd.jsonrpc.JSONRPCException;
import org.json.JSONException;

import com.gainloop.Api.Entity.User;

public class Users extends ApiAbstract {


	public ApiResponseObject<User> create(User user) throws JSONRPCException
	{
		if(user.getId() != 0) {
			throw new ApiException("user id must not set");
		}
		if(user.getFbId() == 0) {
			throw new ApiException("user fbId must be set");
		}
		if(user.getEmail() == null || user.getEmail().length() < 5) {
			throw new ApiException("user email must be set");
		}
		 
		try {
			return new ApiResponseObject<User>(GetClient().callJSONObject("users.create", user.toObject()), User.class);
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}
	
	public ApiResponseObject<User> getById(long id) throws JSONRPCException
	{
		try {
			return new ApiResponseObject<User>(GetClient().callJSONObject("users.getById", id), User.class);
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}
	
	public ApiResponseObject<User> getByFbId(long fbId) throws JSONRPCException
	{
		try {
			return new ApiResponseObject<User>(GetClient().callJSONObject("users.getByFbId", fbId), User.class);
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}
	
	public ApiResponseObject<User> getByEmail(String email) throws JSONRPCException
	{
		try {
			return new ApiResponseObject<User>(GetClient().callJSONObject("users.getByEmail", email), User.class);
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}

	public ArrayList<User> getTopUsers(int page) throws JSONRPCException {
		return getTopUsers(page, 10);
	}

	public ArrayList<User> getTopUsers(int page, int pageLimit)
			throws JSONRPCException {
		if (pageLimit < 1 || pageLimit > 25) {
			throw new ApiException("invalid pageLimit");
		}
		if (page < 1 || page > 50) {
			throw new ApiException("invalid page");
		}

		try {
			ApiResponseArray<User> res = new ApiResponseArray<User>(GetClient().callJSONObject(
					"users.getTopUsers", page, pageLimit), User.class);
			
			if(res.getReturnCode() != 0) {
				throw new ApiException("wrong usage: ", res);
			}
			
			return res.getData();
			
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}
	
}
